<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;padding: 15px 20px;background-color: #f8f9fa;border-radius: 6px;">
        <el-form :inline="true" class="search-form">
          <el-form-item label="客户类型">
            <el-select v-model="crmcustomercategory_id" placeholder="请选择" style="width: 160px;">
              <el-option value="" label="全部" />
              <el-option
                v-for="item in customer_categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              style="width: 380px;"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="kwInput"
              placeholder="输入任意字符进行筛选"
              style="width: 250px;"
              clearable
              @keyup.native.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
            <el-button type="info" icon="el-icon-data-analysis" :loading="listLoading" @click="handleStatistics">统计</el-button>
            <el-button type="success" icon="el-icon-plus" :disabled="listLoading" @click="handleAction('create', '添加')">添加</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @cell-mouse-enter="(m) => m.active=true"
          @cell-mouse-leave="(m) => m.active=false"
          @sort-change="handleSort"
        >
          <el-table-column prop="name" label="客户名称" width="180" />
          <el-table-column prop="company" label="公司名称" width="180" />
          <el-table-column prop="tag" label="标签" width="180">
            <template slot-scope="scope">
              <el-tag
                v-for="tag in scope.row.tag"
                v-if="scope.row.tag.length"
                :key="tag"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="crmcustomercategory__name" label="客户类型" width="120" />
          <el-table-column prop="mail" label="邮箱地址" width="180" />
          <el-table-column prop="phone" label="电话号码" width="150" />
          <el-table-column prop="whatsapp" label="WhatsApp号码" width="150" />
          <el-table-column prop="domain" label="域名" width="180" />
          <el-table-column prop="country" label="国家" width="200">
            <template slot-scope="scope">
              <svg-icon :icon-class="scope.row.country" />{{ getCountryLabel(scope.row.country) }}
            </template>
          </el-table-column>
          <el-table-column prop="source" label="客户来源" width="120" />
          <el-table-column prop="address" label="地址" width="200">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.address" placement="top">
                <div>{{ scope.row.address }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="450">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleCreateOrder(scope.row)">新增订单</el-button>
              <el-button size="mini" type="info" @click="handleViewProfile(scope.row)">客户画像</el-button>
              <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!-- 清除浮动 -->
        <!--        <div style="clear: both;"></div>-->
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <crmeditcustomer
      :customer_row="temp"
      :doaction="action"
      :is-visible="innerDialogVisible"
      @close="innerDialogVisible=false"
    />
    <crmneworder :crmcustomer_id="temp.id" :crmcustomer__name="temp.name" :is-visible="isNewCustomerVisible" @close="isNewCustomerVisible=false" />

    <!-- 客户画像对话框 -->
    <el-dialog
      title="客户画像"
      :visible.sync="profileDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      @closed="handleProfileDialogClose"
    >
      <crmcustomerprofile
        v-if="profileDialogVisible && selectedCustomer.id"
        :crmcustomer_id="selectedCustomer.id"
        :customer-name="selectedCustomer.name"
      />
    </el-dialog>

    <!-- 统计对话框 -->
    <el-dialog
      title="客户统计分析"
      :visible.sync="statisticsVisible"
      width="90%"
      :close-on-click-modal="false"
      @closed="handleStatisticsClose"
    >

      <!-- 统计概览 -->
      <el-row :gutter="20" class="statistics-overview">
        <el-col :span="8">
          <div class="stat-card total-customers">
            <div class="stat-value">{{ statisticsData.totalCustomers }}</div>
            <div class="stat-label">客户总数</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card top-country">
            <div class="stat-value">{{ statisticsData.topCountry }}</div>
            <div class="stat-label">主要国家</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card top-source">
            <div class="stat-value">{{ statisticsData.topSource }}</div>
            <div class="stat-label">主要来源</div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="chart-wrapper">
            <h4>新客户数量趋势</h4>
            <div id="newCustomerChart" style="height: 300px;" />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="chart-wrapper">
            <h4>国家分布</h4>
            <div id="countryChart" style="height: 300px;" />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="chart-wrapper">
            <h4>客户来源分布</h4>
            <div id="sourceChart" style="height: 300px;" />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statisticsVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmcustomer'
import { GetCustomerCategories } from '@/api/crm/crmm'
import qs from 'qs'
import { countries, customer_source, getCountryLabel } from '../../api/crm/crmcommon'
import Crmeditcustomer from './elements/crmeditcustomer'
import Crmneworder from './elements/crmneworder'
import Crmcustomerprofile from './elements/crmcustomerprofile'
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmcustomer',
  components: { Crmneworder, Crmeditcustomer, Crmcustomerprofile },
  data() {
    return {
      isNewCustomerVisible: false,
      data: [],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      crmcustomercategory_id: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      customer_sources: customer_source,
      action: 'create',
      dialogVisible: false,
      title: '',
      temp: {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        whatsapp: '', // WhatsApp number of the customer
        tag: [],
        country: '', // Country of the customer
        crmcustomercategory_id: '', // The category of the customer
        source: '', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      },
      width: '',
      innerDialogVisible: false,
      customer_categories: [],
      dateRange: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '当月',
          onClick(picker) {
            const now = new Date()
            const start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0)
            const end = new Date()
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上个月',
          onClick(picker) {
            const now = new Date()
            const start = new Date(now.getFullYear(), now.getMonth() - 1, 1, 0, 0, 0)
            const end = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近3个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      statisticsVisible: false,
      charts: {
        newCustomerChart: null,
        countryChart: null,
        sourceChart: null
      },
      statisticsData: {
        totalCustomers: 0,
        topCountry: '',
        topSource: ''
      },
      // 客户画像相关
      profileDialogVisible: false,
      selectedCustomer: {
        id: null,
        name: ''
      }
    }
  },
  created() {
    this.handleGetCustomerCategories()
    this.getList()
  },
  beforeDestroy() {
    // 清理图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    handleGetCustomerCategories() {
      GetCustomerCategories().then(response => {
        this.customer_categories = response.data.data
      })
    },
    handleCreateOrder(row) {
      Object.keys(this.temp).forEach(key => {
        if (row[key] !== undefined) this.temp[key] = row[key]
      })
      this.temp.id = row.id
      this.isNewCustomerVisible = true
    },
    // 查看客户画像
    handleViewProfile(row) {
      this.selectedCustomer = {
        id: row.id,
        name: row.name
      }
      this.profileDialogVisible = true
    },
    // 关闭客户画像对话框
    handleProfileDialogClose() {
      this.selectedCustomer = {
        id: null,
        name: ''
      }
    },
    resetTemp() {
      this.temp = {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        whatsapp: '', // WhatsApp number of the customer
        crmcustomercategory_id: '', // The category of the customer
        country: '', // Country of the customer
        tag: [],
        source: '', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        kw: this.kwInput,
        crmcustomercategory_id: this.crmcustomercategory_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }

      // 添加时间范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.start_date = this.dateRange[0]
        params.end_date = this.dateRange[1]
      }

      Get(null, qs.stringify(params))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新客户资料'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除客户:${row.name}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改客户:${row.name}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleStatistics() {
      this.statisticsVisible = true
      this.$nextTick(() => {
        this.getStatisticsData()
      })
    },
    async getStatisticsData() {
      try {
        // 获取统计数据，这里可以调用专门的统计API
        // 暂时使用当前数据进行统计演示
        const params = {
          kw: this.kwInput,
          crmcustomercategory_id: this.crmcustomercategory_id
          // 可以添加更多统计参数
        }

        // 添加时间范围参数
        if (this.dateRange && this.dateRange.length === 2) {
          params.start_date = this.dateRange[0]
          params.end_date = this.dateRange[1]
        }

        const response = await Get(null, qs.stringify(params))
        const data = response.data.data

        // 渲染图表
        this.renderNewCustomerChart(data)
        this.renderCountryChart(data)
        this.renderSourceChart(data)

        // 处理统计数据
        this.statisticsData.totalCustomers = data.length

        // 获取主要国家和来源
        const countryStats = this.processCountryData(data)
        const sourceStats = this.processSourceData(data)

        this.statisticsData.topCountry = countryStats.length > 0 ? countryStats[0].name : '暂无数据'
        this.statisticsData.topSource = sourceStats.length > 0 ? sourceStats[0].name : '暂无数据'
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    renderNewCustomerChart(data) {
      const chartDom = document.getElementById('newCustomerChart')
      if (!chartDom) return

      // 销毁已存在的图表实例
      if (this.charts.newCustomerChart) {
        this.charts.newCustomerChart.dispose()
      }

      this.charts.newCustomerChart = echarts.init(chartDom, 'macarons')

      // 按月统计新客户数量
      const monthlyData = this.processMonthlyData(data)

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: monthlyData.months
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '新客户数量',
          type: 'line',
          data: monthlyData.counts,
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }

      this.charts.newCustomerChart.setOption(option)
    },
    renderCountryChart(data) {
      const chartDom = document.getElementById('countryChart')
      if (!chartDom) return

      // 销毁已存在的图表实例
      if (this.charts.countryChart) {
        this.charts.countryChart.dispose()
      }

      this.charts.countryChart = echarts.init(chartDom, 'macarons')

      // 统计国家分布
      const countryStats = this.processCountryData(data)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '0',
          left: 'center'
        },
        series: [{
          name: '国家分布',
          type: 'pie',
          radius: '70%',
          data: countryStats,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.charts.countryChart.setOption(option)
    },
    renderSourceChart(data) {
      const chartDom = document.getElementById('sourceChart')
      if (!chartDom) return

      // 销毁已存在的图表实例
      if (this.charts.sourceChart) {
        this.charts.sourceChart.dispose()
      }

      this.charts.sourceChart = echarts.init(chartDom, 'macarons')

      // 统计来源分布
      const sourceStats = this.processSourceData(data)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '0',
          left: 'center'
        },
        series: [{
          name: '客户来源',
          type: 'pie',
          radius: ['30%', '70%'],
          data: sourceStats,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.charts.sourceChart.setOption(option)
    },
    processMonthlyData(data) {
      // 处理月度数据
      const monthCount = {}
      const now = new Date()

      // 初始化最近6个月
      for (let i = 5; i >= 0; i--) {
        const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
        const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
        monthCount[key] = 0
      }

      // 统计数据
      data.forEach(item => {
        if (item.create_at) {
          const date = new Date(item.create_at)
          const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
          if (monthCount.hasOwnProperty(key)) {
            monthCount[key]++
          }
        }
      })

      return {
        months: Object.keys(monthCount),
        counts: Object.values(monthCount)
      }
    },
    processCountryData(data) {
      // 处理国家数据
      const countryCount = {}

      data.forEach(item => {
        const country = item.country || '未知'
        const countryName = this.getCountryLabel(country) || country
        countryCount[countryName] = (countryCount[countryName] || 0) + 1
      })

      return Object.entries(countryCount)
        .map(([name, value]) => ({ name, value }))
        .sort((a, b) => b.value - a.value)
    },
    processSourceData(data) {
      // 处理来源数据
      const sourceCount = {}

      data.forEach(item => {
        const source = item.source || '未知'
        sourceCount[source] = (sourceCount[source] || 0) + 1
      })

      return Object.entries(sourceCount)
        .map(([name, value]) => ({ name, value }))
        .sort((a, b) => b.value - a.value)
    },
    handleStatisticsClose() {
      // 清理图表实例
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.dispose()
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.search-form .el-form-item:last-child {
  margin-right: 0;
}

.search-form .el-form-item__label {
  color: #606266;
  font-weight: 500;
}

.search-form .el-button {
  margin-left: 10px;
}

.search-form .el-button:first-child {
  margin-left: 0;
}

.chart-wrapper {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: center;
}

.chart-wrapper h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.stat-card.total-customers .stat-value {
  color: #409EFF;
}

.stat-card.top-country .stat-value {
  color: #E6A23C;
  font-size: 16px;
}

.stat-card.top-source .stat-value {
  color: #F56C6C;
  font-size: 16px;
}
</style>
